package com.laikan.reader.bookfriend.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookstart.activity.HomeActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.MessageAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.MessageBean;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息页
 *
 * @author wxl
 */
public class MessageActivity extends BasicActivity implements OnClickListener {

    private ImageView back_tv;
    private RelativeLayout back_layout;
    private ListView message_list;
    private MessageAdapter mAdapter;
    private ArrayList<MessageBean> mData;
    private LinearLayout no_consume;
    Drawable drawable_back_tv;
    private LoadingDialog loadingDialog;

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        loadingDialog = new LoadingDialog(mContext);
        setContentView(R.layout.lk_message);
        no_consume = (LinearLayout)findViewById(R.id.no_consume);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        message_list = (ListView)findViewById(R.id.message_list);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        mData = new ArrayList<MessageBean>();
        mAdapter = new MessageAdapter(mContext, mData);
        mAdapter.setDatas(mData);
        message_list.setAdapter(mAdapter);
    }

    @Override
    protected void onResume() {
        getData();
        super.onResume();
        MobclickAgent.onResume(this);
        if (SPUtil.getBoolean("message_list", false)) {
            Intent intent = new Intent();
            intent.putExtra("mHtmlUrl", getIntent().getStringExtra("mHtmlUrl"));
            intent.putExtra("title", getIntent().getStringExtra("title"));
            SPUtil.putBoolean("message_" + getIntent().getStringExtra("mesgId"), true);
            intent.setClass(mContext, WebViewActivity.class);
            startActivity(intent);
            SPUtil.putBoolean("message_list", false);
        }
    }

    /**
     * 消息列表网络访问
     */
    private void getData() {
        loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                loadingDialog.dismiss();
                BaseDataBean<BaseListDataBean<MessageBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<MessageBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);

                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {

                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            mData = result.getData().getData();
                            KLog.d("json  mData = " + mData);
                            if (mData.size() != 0) {

                                no_consume.setVisibility(View.GONE);

                            }else {
                                no_consume.setVisibility(View.VISIBLE);
                            }

                            mAdapter.setDatas(mData);
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                loadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。26");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "notification/huodong/list");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "notification/huodong/list", map, null, null, requestListener);

    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        message_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // 跳转消息详情页
                Intent intent = new Intent();
                intent.putExtra("mHtmlUrl", mData.get(arg2).getUrl());
                intent.putExtra("title", mData.get(arg2).getTitle());
                SPUtil.putBoolean("message_" + mData.get(arg2).getId(), true);
                intent.setClass(mContext, WebViewActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                Intent intent = new Intent(mContext, HomeActivity.class);
                startActivity(intent);
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        Intent intent = new Intent(mContext, HomeActivity.class);
        startActivity(intent);
        finish();
    }

}
